package org.tekmob.remindpal.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.tekmob.remindpal.R;

import android.app.Activity;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
/**
 * This activity will be called when Record Audio Button clicked
 * Just can play the audio with different frequency
 * 
 * @author Annisa
 *
 */

public class AndroidAudioRecordActivity extends Activity {

	//Instantiate grequency
	Integer[] freqset = {11025, 16000, 22050, 44100};
	private ArrayAdapter<Integer> adapter;

	Spinner spFrequency;
	ImageButton startRec, stopRec, playBack;

	Boolean recording;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_record_audio);

		startRec = (ImageButton)findViewById(R.id.btnStart);
		stopRec = (ImageButton)findViewById(R.id.btnStop);
		playBack = (ImageButton)findViewById(R.id.btnPlay);

		startRec.setOnClickListener(startRecOnClickListener);
		stopRec.setOnClickListener(stopRecOnClickListener);
		playBack.setOnClickListener(playBackOnClickListener);

		spFrequency = (Spinner)findViewById(R.id.frequency);
		adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, freqset);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spFrequency.setAdapter(adapter);

	}

	//Record Audio when start Button clicked
	OnClickListener startRecOnClickListener
	= new OnClickListener(){

		@Override
		public void onClick(View arg0) {

			Thread recordThread = new Thread(new Runnable(){

				@Override
				public void run() {
					recording = true;
					startRecord();
				}

			});

			recordThread.start();

		}};


		OnClickListener stopRecOnClickListener
		= new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				recording = false;
				Toast.makeText(AndroidAudioRecordActivity.this, "Stop Recording",
						Toast.LENGTH_SHORT).show();
			}};

			OnClickListener playBackOnClickListener
			= new OnClickListener(){

				@Override
				public void onClick(View v) {
					Toast.makeText(AndroidAudioRecordActivity.this, "Play Recording",
							Toast.LENGTH_SHORT).show();
					playRecord();
				}

			};

			/*
			 * Start Recording
			 * 
			 */
			@SuppressWarnings("deprecation")
			private void startRecord(){

				File file = new File(Environment.getExternalStorageDirectory(), "test.pcm"); 

				int sampleFreq = (Integer)spFrequency.getSelectedItem();

				try {
					file.createNewFile();

					OutputStream outputStream = new FileOutputStream(file);
					BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
					DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);

					int minBufferSize = AudioRecord.getMinBufferSize(sampleFreq, 
							AudioFormat.CHANNEL_CONFIGURATION_MONO, 
							AudioFormat.ENCODING_PCM_16BIT);

					short[] audioData = new short[minBufferSize];

					AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
							sampleFreq,
							AudioFormat.CHANNEL_CONFIGURATION_MONO,
							AudioFormat.ENCODING_PCM_16BIT,
							minBufferSize);

					audioRecord.startRecording();

					while(recording){
						int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
						for(int i = 0; i < numberOfShort; i++){
							dataOutputStream.writeShort(audioData[i]);
						}
					}

					audioRecord.stop();
					dataOutputStream.close();

				} catch (IOException e) {
					e.printStackTrace();
				}

			}

			/*
			 * Play the audio with selected frequency
			 */
			void playRecord(){

				File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");

				int shortSizeInBytes = Short.SIZE/Byte.SIZE;

				int bufferSizeInBytes = (int)(file.length()/shortSizeInBytes);
				short[] audioData = new short[bufferSizeInBytes];

				try {
					InputStream inputStream = new FileInputStream(file);
					BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
					DataInputStream dataInputStream = new DataInputStream(bufferedInputStream);

					int i = 0;
					while(dataInputStream.available() > 0){
						audioData[i] = dataInputStream.readShort();
						i++;
					}

					dataInputStream.close();

					int sampleFreq = (Integer)spFrequency.getSelectedItem();

					@SuppressWarnings("deprecation")
					AudioTrack audioTrack = new AudioTrack(
							AudioManager.STREAM_MUSIC,
							sampleFreq,
							AudioFormat.CHANNEL_CONFIGURATION_MONO,
							AudioFormat.ENCODING_PCM_16BIT,
							bufferSizeInBytes,
							AudioTrack.MODE_STREAM);

					audioTrack.play();
					audioTrack.write(audioData, 0, bufferSizeInBytes);


				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			/*
			 * Initiate Option Menu
			 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
			 */
			@Override
			public boolean onCreateOptionsMenu(Menu menu) {
				// Inflate the menu; this adds items to the action bar if it is present.
				getMenuInflater().inflate(R.menu.list_reminder, menu);
				return true;

			}

			/*
			 * Option Menu Handler
			 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
			 */
			@Override
			public boolean onOptionsItemSelected(MenuItem item){
				switch(item.getItemId()) {
				case R.id.new_reminder:
					//click on create item
					Intent newReminder = new Intent(getApplicationContext(),NewReminder.class);
					startActivity(newReminder);
					break; 
				case R.id.show:
					//click on show item
					Intent showReminder = new Intent(getApplicationContext(),ShowReminder.class);
					startActivity(showReminder);
					break;
				case R.id.send:
					//click on send item
					Intent sendReminder = new Intent(getApplicationContext(),SendReminder.class);
					startActivity(sendReminder);
					break;
				}
				return true;	    
			}
}